import dayjs from 'dayjs';
import moment from 'moment';
import { ReactNode } from 'react';
import { ObjectUtil } from './objectUtil';
import { StorageData } from './storageData';
import { getCurrentMonthInfo, getDistrictById } from './utils';

// 类型定义
interface SelectOption {
  value: number | string;
  label: string;
  disabled?: boolean;
}

interface SelectConfig {
  [key: string]: SelectOption[];
}

interface ChangeFieldItem {
  authority: string;
  children?: ChangeFieldItem[];
  table_field: string;
  name: string;
}

interface PermissionItem {
  authority: string;
  children?: PermissionItem[];
}

interface UploadFile {
  id: number;
  url: string;
  img_url?: string;
  name?: string;
  response?: {
    id: number;
    target_dir: string;
    file_name: string;
    tmp_name: string;
  };
}

interface UploadResponse {
  url?: string;
  tmp_name?: string;
  id?: number;
}

// 常量定义
const FIELD_TYPES = {
  UPLOAD: 'upload',
  UPLOAD_FOLD: 'uploadFold',
  CHECKBOX: 'checkbox',
  HIDDEN: 'hidden',
  SELECT: 'select',
  CASCADER: 'cascader',
  DATE: 'date',
  DATE_RANGE: 'dateRange',
  FORM_LIST: 'formList',
  RADIO: 'radio',
  GROUP: 'group',
  DEPENDENCY: 'dependency',
} as const;

const SPAN_CONFIG = {
  [FIELD_TYPES.UPLOAD]: 24,
  [FIELD_TYPES.UPLOAD_FOLD]: 24,
  [FIELD_TYPES.CHECKBOX]: 24,
  [FIELD_TYPES.HIDDEN]: 0,
} as const;

const SELECT_TYPES = ['select', 'cascader', 'date'] as const;

/**
 * 获取字段配置项为select的映射, key为dataIndex, 值为valueEnum形式
 */
export const getColumnSelectMap = (
  fields: FieldProps[],
): Record<string, Record<string, string>> | undefined => {
  try {
    const chxMergeSelect = localStorage.getItem('chxMergeSelect');
    if (!chxMergeSelect) return undefined;

    const selectConfig: SelectConfig = JSON.parse(chxMergeSelect);
    const selectFields = fields.filter(
      (field: FieldProps) => field.valueType === FIELD_TYPES.SELECT,
    );

    const map: Record<string, Record<string, string>> = {};

    selectFields.forEach((field: FieldProps) => {
      if (field.sign && selectConfig[field.sign]) {
        const valueEnum: Record<string, string> = {};
        selectConfig[field.sign].forEach((item: SelectOption) => {
          valueEnum[item.value] = item.label;
        });
        map[field.dataIndex] = valueEnum;
      } else {
        map[field.dataIndex] = {};
      }
    });

    return map;
  } catch (error) {
    console.error('获取列选择映射失败:', error);
    return undefined;
  }
};

/**
 * 根据菜单获取可变更字段配置项
 */
export const getChangeFields = (fields: FieldProps[], changeAuth: string): Record<string, any> => {
  try {
    const permissionsStr = localStorage.getItem('adminPermissions');
    if (!permissionsStr) return {};

    const permissions: PermissionItem[] = JSON.parse(permissionsStr);
    let changeFields: any[] = [];

    const findChangeBtn = (data: PermissionItem[]) => {
      data.forEach((item: PermissionItem) => {
        if (item.authority === changeAuth) {
          changeFields = item.children || [];
        } else if (item.children) {
          findChangeBtn(item.children);
        }
      });
    };

    findChangeBtn(permissions);

    const changeFieldsMap: Record<string, any> = {};
    changeFields.forEach((item: ChangeFieldItem) => {
      // 从json配置中找到变更项
      const changeItem = fields.find((field: FieldProps) => field.dataIndex === item.table_field);
      if (changeItem) {
        changeFieldsMap[item.table_field] = {
          ...changeItem,
          label: item.name,
          value: item.table_field,
        };
      }
    });

    return changeFieldsMap;
  } catch (error) {
    console.error('获取变更字段失败:', error);
    return {};
  }
};

export type FieldsVisableType = 'list' | 'add' | 'detail' | 'edit' | string;

/**
 * 字段工具类
 */
export default class FieldsUtils {
  /**
   * 级联选择器配置
   */
  static configCascaderField(field: FieldProps): FieldProps {
    try {
      const districtData = JSON.parse(StorageData.chxMergeDistrict);
      return {
        ...field,
        fieldProps: {
          options: districtData,
          fieldNames: { label: 'name', value: 'id' },
          showSearch: true,
          ...(field.fieldProps || {}),
        },
        transform:
          field.transform ||
          ((value: any) => ({
            first_id: value[0],
            second_id: value[1],
            category_id: value[2],
          })),
      };
    } catch (error) {
      console.error('配置级联选择器失败:', error);
      return field;
    }
  }

  /**
   * 日期区间配置
   */
  static configDateRangeField(field: FieldProps): FieldProps {
    return {
      ...field,
      transform: (value: any) => {
        if (!Array.isArray(value) || value.length !== 2) return {};

        const start = value[0];
        const end = moment(value[1]).add(1, 'day').subtract(1, 's').format('YYYY-MM-DD HH:mm:ss');
        return ObjectUtil.setValue({}, field.dataIndex as string, [start, end]);
      },
    };
  }

  /**
   * 下拉框配置
   */
  static configSelectField(field: FieldProps): FieldProps {
    try {
      const chxMergeSelect = StorageData.chxMergeSelect;
      let selectConfig: SelectConfig = {};

      if (chxMergeSelect) {
        selectConfig = JSON.parse(chxMergeSelect);
      }

      if (!field.sign) return field;

      let options = selectConfig[field.sign] || [];

      // 处理禁用项
      if (field.disabledItem) {
        const disabledItems = field.disabledItem.split(',').map(Number);
        options = options.map((item: SelectOption) => ({
          ...item,
          disabled: disabledItems.includes(item.value as number),
        }));
      }

      // 处理过滤项
      if (field.fliterItem) {
        const filterItems = field.fliterItem.split(',').map(Number);
        options = options.filter(
          (item: SelectOption) => !filterItems.includes(item.value as number),
        );
      }

      return {
        ...field,
        fieldProps: {
          options: [...options],
          ...field.fieldProps,
        },
        renderText:
          field.renderText ||
          ((text: any) => {
            if (!text) return text;
            // 处理多选数据在table中的显示
            return (
              String(text)
                ?.split?.(',')
                .map((v) => (Number.isNaN(Number(v)) ? v : Number(v))) || text
            );
          }),
        transform: (value: any) => {
          // 处理多选数据提交
          return Array.isArray(value) ? value.join(',') : value;
        },
        convertValue:
          field.convertValue ||
          ((value: any) => {
            // number类型并且找不到选项就返回'-'
            if (typeof value === 'number') {
              return options.findIndex((v: SelectOption) => v.value === value) !== -1 ? value : '-';
            }
            return value;
          }),
      };
    } catch (error) {
      console.error('配置下拉框失败:', error);
      return field;
    }
  }

  /**
   * 多选框配置
   */
  static configCheckboxField(field: FieldProps): FieldProps {
    try {
      const chxMergeSelect = StorageData.chxMergeSelect;
      const selectConfig: SelectConfig = JSON.parse(chxMergeSelect || '{}');

      if (!field.sign) return field;

      const options = selectConfig[field.sign] || [];
      return {
        ...field,
        fieldProps: {
          options: [...options],
        },
      };
    } catch (error) {
      console.error('配置多选框失败:', error);
      return field;
    }
  }

  /**
   * 日期字段配置
   */
  static configDateField(field: FieldProps): FieldProps {
    return {
      ...field,
      fieldProps: {
        ...field.fieldProps,
        style: { width: '100%' },
      },
    };
  }

  /**
   * 表单列表字段配置
   */
  static configFormListField(field: FieldProps): FieldProps {
    return {
      ...field,
      fieldProps: {
        ...field.fieldProps,
        copyIconProps: false,
        deleteIconProps: true,
      },
    };
  }

  /**
   * 上传字段配置
   */
  static configUploadField(field: FieldProps): FieldProps {
    let title: string = field.title || field.fieldProps?.title || '';

    ObjectUtil.setValue(field, 'title', title);
    ObjectUtil.setValue(field, 'formItemProps.labelCol', { span: 24 });
    ObjectUtil.setValue(field, 'transform', (value: UploadFile[], name: string) => ({
      [name]: value.map((v) => ({ url: v.url })),
    }));

    return field;
  }

  /**
   * 文件夹上传字段配置
   */
  static configUploadFoldField(field: FieldProps): FieldProps {
    let title: string = field.title || field.fieldProps?.title || '';

    if (!title.includes('单张图片不得大于5M')) {
      const { min = 0, max } = field.fieldProps || {};

      if (min && max) {
        title += `(至少${min}张，最多${max}张，不得大于5M)`;
      } else if (min) {
        title += `(至少${min}张，不得大于5M)`;
      } else if (max) {
        title += `(最多${max}张，不得大于5M)`;
      }
    }

    ObjectUtil.setValue(field, 'title', title);
    ObjectUtil.setValue(field, 'formItemProps.labelCol', { span: 24 });
    ObjectUtil.setValue(field, 'transform', (value: UploadFile[], name: string) => ({
      [name]: value.map((v) => ({ ...v })),
    }));

    return field;
  }

  /**
   * 配置字段样式
   */
  static configStyle(field: FieldProps): FieldProps {
    return ObjectUtil.setValue(field, 'fieldProps.style.width', '100%');
  }

  /**
   * 处理依赖字段
   */
  static handleDependency(field: FieldProps): FieldProps {
    const { correlation_dataIndex, correlation_value } = field;

    // 验证依赖配置
    if (typeof correlation_dataIndex !== 'string' && !Array.isArray(correlation_dataIndex)) {
      return field;
    }

    if (!correlation_dataIndex?.length || correlation_value === undefined) {
      return field;
    }

    // 支持多个依赖项和依赖值用逗号分割
    const depName =
      typeof correlation_dataIndex === 'string'
        ? correlation_dataIndex.split(',')
        : correlation_dataIndex;

    let depValues = correlation_value;
    if (!Array.isArray(depValues)) {
      switch (typeof correlation_value) {
        case 'string':
          depValues = correlation_value.split(',');
          break;
        default:
          depValues = [correlation_value];
      }
    }

    if (depName.length !== depValues.length) {
      throw new Error(`依赖项和依赖值的长度必须一致: ${depName} vs ${depValues}`);
    }

    return {
      ...field,
      name: depName,
      valueType: FIELD_TYPES.DEPENDENCY,
      key: field.key,
      columns: (data: any) => {
        const exps = depName.map((k: string, i: number) => {
          const depV = depValues[i];
          if (!depV) return true; // 没有依赖值, 表示任意值可通过

          const currentV = data[k];
          if (!currentV) return false; // 有依赖值,但是依赖项没值 拒绝通过

          const r = RegExp(`^${depV}$`);
          return r.test(currentV); // 通过正则验证是否匹配
        });

        if (exps.every((v) => v === true)) {
          return [
            {
              ...field,
              dataIndex: field.dataIndex.split('.'),
            },
          ];
        }
        return [];
      },
    } as unknown as FieldProps;
  }

  /**
   * 根据valueType配置字段
   */
  static configField(field: FieldProps): FieldProps {
    let _field = ObjectUtil.deepClone(field);

    this.configStyle(_field);

    switch (_field.valueType) {
      case FIELD_TYPES.CASCADER:
        _field = this.configCascaderField(_field);
        break;
      case FIELD_TYPES.SELECT:
      case FIELD_TYPES.RADIO:
        _field = this.configSelectField(_field);
        break;
      case FIELD_TYPES.CHECKBOX:
        _field = this.configCheckboxField(_field);
        break;
      case FIELD_TYPES.DATE_RANGE:
        _field = this.configDateRangeField(_field);
        break;
      case FIELD_TYPES.DATE:
        _field = this.configDateField(_field);
        break;
      case FIELD_TYPES.FORM_LIST:
        _field = this.configFormListField(_field);
        break;
      case FIELD_TYPES.UPLOAD:
        _field = this.configUploadField(_field);
        break;
      case FIELD_TYPES.UPLOAD_FOLD:
        _field = this.configUploadFoldField(_field);
        break;
    }

    // 配置验证规则
    const rule: any = {
      required: _field.required,
      message: `请${SELECT_TYPES.includes(_field.valueType as any) ? '选择' : '输入'}${
        _field.title
      }`,
    };

    if (_field.valueType === FIELD_TYPES.UPLOAD || _field.valueType === FIELD_TYPES.UPLOAD_FOLD) {
      rule.message = `请上传${_field.title}`;
      rule.type = 'array';
      rule.min = _field.fieldProps?.min || 0;
      rule.max = _field.fieldProps?.max || 9999;
    }

    ObjectUtil.setValue(_field, 'formItemProps.rules', [rule]);
    return Object.assign({}, _field);
  }

  /**
   * 根据类型过滤字段
   */
  static filterByType(fields: FieldProps[], type: FieldsVisableType): FieldProps[] {
    try {
      // 验证输入参数
      if (!Array.isArray(fields)) {
        console.error('filterByType: fields 参数不是数组:', fields);
        return [];
      }

      if (!type) {
        console.error('filterByType: type 参数无效:', type);
        return [];
      }

      switch (type) {
        case 'add':
          return fields.filter((v) => !!v.add);
        case 'detail':
          return fields.filter((v) => !!v.detail);
        case 'edit':
          return fields.filter((v) => !!v.edit);
        case 'list':
          return fields
            .filter((v) => !!v.list || !!v.search)
            .map((v) => ({
              ...v,
              hideInSearch: !v.search,
              hideInTable: !v.list,
            }));
        default:
          return fields.filter((v) => !!v[type]);
      }
    } catch (error) {
      console.error('filterByType 方法执行失败:', error);
      return [];
    }
  }

  /**
   * 处理字段配置
   */
  static handleFields(
    fields: FieldProps[],
    customHandle?: (field: FieldProps) => FieldProps,
  ): FieldProps[] {
    try {
      // 验证输入参数
      if (!Array.isArray(fields)) {
        console.error('handleFields: fields 参数不是数组:', fields);
        return [];
      }

      const _customHandle = customHandle || ((field) => field);
      const layout = fields.find((v) => v.dataIndex === 'layout');
      const span = layout?.column ? 24 / layout.column : 24;

      return fields
        .filter((v) => v.dataIndex !== 'layout') // 去除layout
        .map((v) => {
          try {
            let field = this.configField(v);
            field = this.configFieldSpan(field, span);
            // 配置排序
            if (typeof field.sorter === 'number') {
              field.sorter = { multiple: field.sorter };
              const key = Array.isArray(field.dataIndex)
                ? field.dataIndex.join('.')
                : field.dataIndex;
              field.key = key;
              field.sortOrder = field.defaultSortOrder;
            }

            // 配置默认值
            if (field.initialValue === 'initDate') {
              field.initialValue =
                field.valueType === 'dateMonth' ? getCurrentMonthInfo() : new Date();
            }

            if (field.initialValue === 'initRange') {
              field.initialValue = [dayjs().startOf('month'), dayjs().endOf('month')];
            }

            field = _customHandle(field);
            field = this.handleDependency(field);

            field.dataIndex =
              typeof v.dataIndex === 'string' ? v.dataIndex.split('.') : v.dataIndex;
            field.category =
              layout?.has_category === 1 ? layout?.category?.[v.category || ''] : undefined;

            return field;
          } catch (fieldError) {
            console.error('处理字段失败:', v, fieldError);
            return v; // 返回原始字段
          }
        });
    } catch (error) {
      console.error('handleFields 方法执行失败:', error);
      return [];
    }
  }

  /**
   * 配置字段占位大小
   */
  static configFieldSpan(field: FieldProps, span = 6): FieldProps {
    const width = SPAN_CONFIG[field.valueType as keyof typeof SPAN_CONFIG];
    return Object.assign({}, field, {
      colProps: {
        span: width ?? span,
        ...field.colProps,
      },
    });
  }

  /**
   * 添加操作栏
   */
  static addOperate(
    fields: FieldProps[],
    render: (text: ReactNode, record: any) => ReactNode,
    width = 200,
  ): FieldProps[] {
    return [
      ...fields,
      {
        title: '操作',
        dataIndex: 'operate',
        list: 1,
        search: false,
        align: 'center',
        fixed: 'right',
        render,
        valueType: FIELD_TYPES.HIDDEN,
        width,
      },
    ];
  }

  /**
   * 按分类分离字段
   */
  static separateFields(
    fields: FieldProps[],
  ): (
    | FieldProps
    | { title: string; valueType: 'group'; rowProps: { gutter: number }; columns: FieldProps[] }
  )[] {
    const unCategory: FieldProps[] = [];
    const categoryColumnsMap: Record<string, FieldProps[]> = {};

    fields.forEach((item: FieldProps) => {
      if (item.category) {
        if (!categoryColumnsMap[item.category]) {
          categoryColumnsMap[item.category] = [];
        }
        categoryColumnsMap[item.category].push(item);
      } else {
        unCategory.push(item);
      }
    });

    const categorizedFields = Object.keys(categoryColumnsMap).map((key) => ({
      title: key,
      valueType: FIELD_TYPES.GROUP,
      rowProps: { gutter: 30 },
      columns: categoryColumnsMap[key],
    }));

    return [...categorizedFields, ...unCategory];
  }

  /**
   * 获取列配置
   */
  static getColumns(fields: FieldProps[], customColumn: Record<string, any>): FieldProps[] {
    try {
      // 验证输入参数
      if (!Array.isArray(fields)) {
        console.error('getColumns: fields 参数不是数组:', fields);
        return [];
      }

      if (!customColumn || typeof customColumn !== 'object') {
        console.error('getColumns: customColumn 参数无效:', customColumn);
        return [];
      }

      const customKeys = Object.keys(customColumn);

      // 处理自定义操作
      let _fields = this.handleFields(fields, (field: FieldProps) => {
        if (!customKeys.length || !customKeys.includes(field.dataIndex)) {
          return field;
        }
        return Object.assign({}, field, customColumn[field.dataIndex]);
      });

      // 添加操作栏
      if (customColumn.operate?.render) {
        _fields = this.addOperate(_fields, customColumn.operate.render, customColumn.operate.width);
      }

      return _fields;
    } catch (error) {
      console.error('getColumns 方法执行失败:', error);
      return [];
    }
  }

  /**
   * 处理图片显示
   */
  static handleImageDisplay(fields: FieldProps[], data: any): any {
    let _data = data;
    const filesToProcess = _data?.all_files || _data?.files;

    // 处理文件数据
    filesToProcess?.forEach((v: any) => {
      let key = 'upload' + v.sorts;
      if (v.upload && v.upload !== '') {
        key = v.upload;
      }

      if (!Array.isArray(_data[key])) {
        _data[key] = [];
      }

      if (v.url?.startsWith('https')) {
        _data[key].push({
          id: v.id,
          url: v.url,
          img_url: v.img_url,
          name: v.url.split('/').pop(),
        });
      }
    });

    // 处理空图片数据
    const processField = (v: any) => {
      if (v.valueType === FIELD_TYPES.UPLOAD || v.valueType === FIELD_TYPES.UPLOAD_FOLD) {
        const images = ObjectUtil.getValue(_data, v.dataIndex);
        if (!Array.isArray(images)) {
          _data = ObjectUtil.setValue(_data, v.dataIndex, []);
        }
      } else if (v.valueType === FIELD_TYPES.GROUP) {
        v.columns?.forEach(processField);
      }
    };

    fields.forEach(processField);
    return data;
  }

  /**
   * 获取表单展示数据
   */
  static async getFormShowData(
    fields: FieldProps[],
    data: Record<string, any>,
  ): Promise<Record<string, any>> {
    const _data: Record<string, any> = {};

    for (const field of fields) {
      const value = await this.getFormShowText(field, ObjectUtil.getValue(data, field.dataIndex));
      ObjectUtil.setValue(_data, field.dataIndex, value);
    }

    return _data;
  }

  /**
   * 获取展示字段文本
   */
  static async getFormShowText(field: FieldProps, value: any): Promise<any> {
    if (value === undefined || value === null) {
      return undefined;
    }

    const valueType = field.valueType;
    switch (valueType) {
      case 'input':
        return value;
      case 'money':
        return '¥' + Number(value).toFixed(2);
      case 'select':
      case 'radio':
        return await this.getSelectFormShowText(field, value);
      case 'cascader':
        return getDistrictById(value);
      default:
        return value;
    }
  }

  /**
   * 获取选择字段展示文本
   */
  static async getSelectFormShowText(field: FieldProps, value: any): Promise<any> {
    let options = field.fieldProps?.options;

    if (!options) {
      try {
        const chxMergeSelect = localStorage.getItem('chxMergeSelect');
        const selectConfig: SelectConfig = JSON.parse(chxMergeSelect || '{}');
        options = selectConfig[field.sign!];
      } catch (error) {
        console.error('解析选择配置失败:', error);
        return value;
      }
    }

    if (Array.isArray(options)) {
      return options.find((v: SelectOption) => v.value === value)?.label || value;
    }

    const request = field?.request;
    if (typeof request === 'function') {
      try {
        const fieldNames = field.fieldProps?.fieldNames || { value: 'value', label: 'label' };
        const res: any[] = await request({ keyWords: null });

        if (Array.isArray(value)) {
          return (
            res
              .filter((v) => value.includes(v[fieldNames.value]))
              ?.map((v) => v[fieldNames.label])
              ?.join(',') || value
          );
        } else {
          return res.find((v: any) => v[fieldNames.value] === value)?.[fieldNames.label] || value;
        }
      } catch (error) {
        console.error('请求选择数据失败:', error);
        return value;
      }
    }

    return value;
  }

  /**
   * 根据dataIndex查找字段
   */
  static getFieldFormDataIndex(
    fields: FieldProps[],
    dataIndex: string | string[],
  ): FieldProps | undefined {
    const getKey = (fieldDataIndex: string | string[]) =>
      Array.isArray(fieldDataIndex) ? fieldDataIndex?.join('.') : fieldDataIndex;

    const newFields = fields.reduce(
      (p: FieldProps[], v) =>
        v.valueType === FIELD_TYPES.GROUP ? p.concat(v.columns) : p.concat(v),
      [],
    );

    return newFields.find((v) => getKey(v.dataIndex) === getKey(dataIndex));
  }

  /**
   * 获取编辑参数
   */
  static getEditParams(fields: FieldProps[], data: Record<string, any>): Record<string, any> {
    fields.forEach((group) => {
      group.columns?.forEach((column: any) => {
        if (column.edit_disabled === 1) {
          const keys = column.dataIndex;
          let current = data;

          // 遍历 dataIndex 找到对应的键
          for (let i = 0; i < keys.length - 1; i++) {
            current = current[keys[i]];
            if (current === undefined) return;
          }

          // 检查 disabled_on_submit 字段
          if (column.disabled_on_submit !== 1) {
            console.log('删除的字段', keys[keys.length - 1], current[keys[keys.length - 1]]);
            delete current[keys[keys.length - 1]];
          }
        }
      });
    });

    return data;
  }

  /**
   * 获取新增参数
   */
  static getAddParams(fields: FieldProps[], data: Record<string, any>): Record<string, any> {
    fields.forEach((group) => {
      if (group.add_disabled === 1) {
        const keys = group.dataIndex;
        let current = data;

        // 遍历 dataIndex 找到对应的键
        for (let i = 0; i < keys.length - 1; i++) {
          current = current[keys[i]];
          if (current === undefined) return;
        }

        const initialValue = group.initialValue;
        if (initialValue === undefined || initialValue === '') {
          if (group.disabled_on_submit !== 1) {
            console.log('删除的字段', keys[keys.length - 1], current[keys[keys.length - 1]]);
            delete current[keys[keys.length - 1]];
          }
        }
      }
    });

    return data;
  }

  /**
   * 获取上传列参数
   */
  static getUploadColumnParams(
    fields: FieldProps[],
    data: Record<string, any>,
  ): Record<string, any> {
    let current = data;
    data.uploads = {};

    fields.forEach((group) => {
      group.columns?.forEach((column: any) => {
        if (column.valueType === FIELD_TYPES.UPLOAD_FOLD) {
          let currentUpload = current[column.dataIndex[0]];
          currentUpload = currentUpload.map((v: UploadFile): UploadResponse => {
            if (v?.response?.id === 0) {
              return {
                url: v.response.target_dir + '/' + v.response.file_name,
                tmp_name: v.response.tmp_name,
              };
            } else {
              return { id: v.id };
            }
          });

          data.uploads[column.dataIndex[0]] = currentUpload;
          delete current[column.dataIndex[0]];
        }
      });
    });

    return data;
  }

  /**
   * 获取上传参数
   */
  static getUploadParams(fields: FieldProps[], data: Record<string, any>): Record<string, any> {
    let current = data;
    data.uploads = {};

    fields.forEach((group) => {
      if (group.valueType === FIELD_TYPES.UPLOAD_FOLD) {
        let currentUpload = current[group.dataIndex[0]];
        if (currentUpload) {
          currentUpload = currentUpload.map((v: UploadFile): UploadResponse => {
            if (v?.response?.id === 0) {
              return {
                url: v.response.target_dir + '/' + v.response.file_name,
                tmp_name: v.response.tmp_name,
              };
            } else {
              return { id: v.id };
            }
          });

          data.uploads[group.dataIndex[0]] = currentUpload;
          delete current[group.dataIndex[0]];
        }
      }
    });

    return data;
  }

  /**
   * 获取选择文本
   */
  static getSelectText(index: string, value: string): string {
    try {
      const chxMergeSelect = localStorage.getItem('chxMergeSelect');
      const selectConfig: SelectConfig = JSON.parse(chxMergeSelect || '{}');
      const options = selectConfig[index];

      if (!options) return '-';

      const item = options.find((field: SelectOption) => field.value === value);
      return item?.label || '-';
    } catch (error) {
      console.error('获取选择文本失败:', error);
      return '-';
    }
  }
}
